import 'dart:convert';
import 'dart:math';
import '../models/exhibition.dart';

/// 展览服务类
class ExhibitionService {
  static final ExhibitionService _instance = ExhibitionService._internal();
  factory ExhibitionService() => _instance;
  ExhibitionService._internal();

  // 模拟数据存储
  final List<Exhibition> _exhibitions = [];
  final List<String> _userBookings = []; // 用户预约记录
  final List<String> _userFavorites = []; // 用户收藏记录

  /// 初始化模拟数据
  void initializeMockData() {
    if (_exhibitions.isNotEmpty) return;

    final now = DateTime.now();
    _exhibitions.addAll([
      Exhibition(
        id: '1',
        title: '千年丝路：古代丝绸之路文物展',
        description: '展示古代丝绸之路沿线的珍贵文物，包括丝绸、陶瓷、金银器等，再现丝路贸易的繁荣景象。通过200余件精美文物，带您穿越时空，感受千年丝路的文化魅力。',
        startDate: now.subtract(const Duration(days: 30)),
        endDate: now.add(const Duration(days: 60)),
        venue: '国家博物馆',
        address: '北京市东城区东长安街16号',
        type: ExhibitionType.permanent,
        status: ExhibitionStatus.ongoing,
        exhibits: [
          ExhibitItem(
            id: '1-1',
            name: '唐代三彩骆驼载乐俑',
            description: '唐代丝路贸易的象征，骆驼背上载有乐队，展现了丝路文化交流的繁荣。',
            imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=Tang%20dynasty%20tri-color%20camel%20figurine%20with%20musicians&image_size=square',
            period: '唐代（618-907年）',
            origin: '西安',
            material: '陶瓷',
            dimensions: '高58cm，长43cm',
            significance: '反映了唐代丝绸之路贸易的繁荣和文化交流',
          ),
          ExhibitItem(
            id: '1-2',
            name: '波斯银币',
            description: '萨珊王朝银币，见证了古代中西贸易往来。',
            imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=ancient%20Persian%20silver%20coin%20Sassanid%20dynasty&image_size=square',
            period: '萨珊王朝（224-651年）',
            origin: '波斯',
            material: '银',
            dimensions: '直径3.2cm',
            significance: '丝绸之路货币流通的重要证据',
          ),
        ],
        virtualTourUrl: 'https://virtual-tour.example.com/silk-road',
        images: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=ancient%20silk%20road%20exhibition%20hall%20with%20artifacts&image_size=landscape_4_3',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=silk%20road%20cultural%20relics%20display&image_size=landscape_4_3',
        ],
        curatorName: '李文华',
        curatorInfo: '中国社会科学院考古研究所研究员，丝绸之路文化研究专家',
        ticketPrice: 30.0,
        maxVisitors: 500,
        currentVisitors: 320,
        openingHours: '9:00-17:00（周一闭馆）',
        facilities: ['语音导览', '无障碍通道', '休息区', '纪念品商店'],
        visitingGuidelines: {
          'duration': '建议参观时长2-3小时',
          'photography': '部分展品可拍照，请勿使用闪光灯',
          'group_size': '团体参观请提前预约',
        },
        createdAt: now.subtract(const Duration(days: 45)),
        updatedAt: now.subtract(const Duration(hours: 3)),
        isFeatured: true,
        rating: 4.8,
        reviewCount: 1256,
        tags: ['丝绸之路', '历史文物', '文化交流', '古代贸易'],
      ),
      Exhibition(
        id: '2',
        title: '匠心传承：中国传统工艺美术展',
        description: '汇集全国各地传统工艺美术精品，包括景泰蓝、漆器、刺绣、雕刻等，展现中华传统工艺的精湛技艺和文化内涵。',
        startDate: now.add(const Duration(days: 15)),
        endDate: now.add(const Duration(days: 90)),
        venue: '中国美术馆',
        address: '北京市东城区五四大街1号',
        type: ExhibitionType.special,
        status: ExhibitionStatus.upcoming,
        exhibits: [
          ExhibitItem(
            id: '2-1',
            name: '清代掐丝珐琅花卉纹瓶',
            description: '清代宫廷御用景泰蓝作品，工艺精湛，色彩绚丽。',
            imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=Qing%20dynasty%20cloisonne%20enamel%20vase%20with%20floral%20patterns&image_size=square',
            period: '清代（1644-1912年）',
            origin: '北京',
            material: '铜胎掐丝珐琅',
            dimensions: '高35cm，口径12cm',
            significance: '代表了中国景泰蓝工艺的最高水平',
          ),
        ],
        virtualTourUrl: '',
        images: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20Chinese%20crafts%20exhibition%20hall&image_size=landscape_4_3',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=Chinese%20traditional%20handicrafts%20display&image_size=landscape_4_3',
        ],
        curatorName: '王美玲',
        curatorInfo: '中央美术学院教授，传统工艺美术研究专家',
        ticketPrice: 25.0,
        maxVisitors: 300,
        currentVisitors: 0,
        openingHours: '9:00-17:00（周一闭馆）',
        facilities: ['专业讲解', '互动体验区', '工艺演示'],
        visitingGuidelines: {
          'duration': '建议参观时长1.5-2小时',
          'photography': '允许拍照，请勿触摸展品',
          'workshop': '每日14:00有工艺演示',
        },
        createdAt: now.subtract(const Duration(days: 20)),
        updatedAt: now.subtract(const Duration(hours: 1)),
        isFeatured: true,
        rating: 4.7,
        reviewCount: 89,
        tags: ['传统工艺', '美术', '景泰蓝', '刺绣'],
      ),
      Exhibition(
        id: '3',
        title: '民俗风情：中国传统节日文化展',
        description: '通过丰富的实物、图片和多媒体展示，全面介绍中国传统节日的起源、习俗和文化内涵，让观众深入了解中华民族的节日文化。',
        startDate: now.subtract(const Duration(days: 10)),
        endDate: now.add(const Duration(days: 30)),
        venue: '民俗博物馆',
        address: '北京市朝阳区民俗街88号',
        type: ExhibitionType.temporary,
        status: ExhibitionStatus.ongoing,
        exhibits: [
          ExhibitItem(
            id: '3-1',
            name: '清代年画《门神》',
            description: '传统木版年画，寓意驱邪避凶，保佑平安。',
            imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20Chinese%20New%20Year%20door%20god%20painting&image_size=square',
            period: '清代',
            origin: '天津杨柳青',
            material: '纸本彩印',
            dimensions: '长50cm，宽35cm',
            significance: '反映了中国传统年俗文化',
          ),
        ],
        virtualTourUrl: 'https://virtual-tour.example.com/folk-culture',
        images: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=Chinese%20traditional%20festival%20culture%20exhibition&image_size=landscape_4_3',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=folk%20customs%20display%20museum&image_size=landscape_4_3',
        ],
        curatorName: '张民俗',
        curatorInfo: '北京民俗学会会长，民俗文化研究专家',
        ticketPrice: 20.0,
        maxVisitors: 200,
        currentVisitors: 156,
        openingHours: '9:00-16:30（周一闭馆）',
        facilities: ['互动体验', '民俗表演', '手工制作'],
        visitingGuidelines: {
          'duration': '建议参观时长1-1.5小时',
          'photography': '允许拍照分享',
          'activities': '周末有民俗体验活动',
        },
        createdAt: now.subtract(const Duration(days: 25)),
        updatedAt: now.subtract(const Duration(hours: 6)),
        isFeatured: false,
        rating: 4.5,
        reviewCount: 234,
        tags: ['民俗', '传统节日', '年画', '文化'],
      ),
    ]);
  }

  /// 获取所有展览
  Future<List<Exhibition>> getAllExhibitions() async {
    await Future.delayed(const Duration(milliseconds: 500));
    return List.from(_exhibitions);
  }

  /// 根据筛选条件获取展览
  Future<List<Exhibition>> getExhibitionsByFilter(ExhibitionFilter filter) async {
    await Future.delayed(const Duration(milliseconds: 300));
    
    switch (filter) {
      case ExhibitionFilter.all:
        return List.from(_exhibitions);
      case ExhibitionFilter.upcoming:
        return _exhibitions.where((e) => e.status == ExhibitionStatus.upcoming).toList();
      case ExhibitionFilter.ongoing:
        return _exhibitions.where((e) => e.status == ExhibitionStatus.ongoing).toList();
      case ExhibitionFilter.completed:
        return _exhibitions.where((e) => e.status == ExhibitionStatus.completed).toList();
      case ExhibitionFilter.traditional:
        return _exhibitions.where((e) => e.type == ExhibitionType.permanent).toList();
      case ExhibitionFilter.folk:
        return _exhibitions.where((e) => e.type == ExhibitionType.temporary).toList();
      case ExhibitionFilter.historical:
        return _exhibitions.where((e) => e.type == ExhibitionType.special).toList();
      case ExhibitionFilter.modern:
        return _exhibitions.where((e) => e.type == ExhibitionType.virtual).toList();
      case ExhibitionFilter.interactive:
        return _exhibitions.where((e) => e.type == ExhibitionType.virtual).toList();
      case ExhibitionFilter.featured:
        return _exhibitions.where((e) => e.isFeatured).toList();
      case ExhibitionFilter.ended:
        return _exhibitions.where((e) => e.status == ExhibitionStatus.completed).toList();
      case ExhibitionFilter.virtual:
        return _exhibitions.where((e) => e.type == ExhibitionType.virtual).toList();
      case ExhibitionFilter.hot:
        return _exhibitions.where((e) => e.rating >= 4.5).toList();
      case ExhibitionFilter.bookmarked:
        return _exhibitions.where((e) => e.isFeatured).toList();
      case ExhibitionFilter.free:
        return _exhibitions.where((e) => e.ticketPrice == 0).toList();
    }
  }

  /// 获取热门展览
  Future<List<Exhibition>> getHotExhibitions({int limit = 5}) async {
    await Future.delayed(const Duration(milliseconds: 300));
    final hotExhibitions = List.from(_exhibitions)
      ..sort((a, b) => (b.rating * b.reviewCount).compareTo(a.rating * a.reviewCount));
    return hotExhibitions.take(limit).toList();
  }

  /// 获取推荐展览
  Future<List<Exhibition>> getRecommendedExhibitions({int limit = 5}) async {
    await Future.delayed(const Duration(milliseconds: 300));
    final recommended = _exhibitions.where((e) => 
      e.status == ExhibitionStatus.upcoming || e.status == ExhibitionStatus.ongoing
    ).toList()
      ..shuffle(Random());
    return recommended.take(limit).toList();
  }

  /// 获取精选展览
  Future<List<Exhibition>> getFeaturedExhibitions({int limit = 3}) async {
    await Future.delayed(const Duration(milliseconds: 300));
    return _exhibitions.where((e) => e.isFeatured).take(limit).toList();
  }

  /// 根据ID获取展览详情
  Future<Exhibition?> getExhibitionById(String id) async {
    await Future.delayed(const Duration(milliseconds: 200));
    try {
      return _exhibitions.firstWhere((e) => e.id == id);
    } catch (e) {
      return null;
    }
  }

  /// 搜索展览
  Future<List<Exhibition>> searchExhibitions(String query) async {
    await Future.delayed(const Duration(milliseconds: 400));
    if (query.isEmpty) return [];
    
    final lowerQuery = query.toLowerCase();
    return _exhibitions.where((exhibition) {
      return exhibition.title.toLowerCase().contains(lowerQuery) ||
             exhibition.description.toLowerCase().contains(lowerQuery) ||
             exhibition.tags.any((tag) => tag.toLowerCase().contains(lowerQuery)) ||
             exhibition.curatorName.toLowerCase().contains(lowerQuery);
    }).toList();
  }

  /// 预约参观
  Future<bool> bookExhibition(String exhibitionId, String userId, DateTime visitDate) async {
    await Future.delayed(const Duration(milliseconds: 500));
    
    final exhibition = await getExhibitionById(exhibitionId);
    if (exhibition == null || !exhibition.canBook) {
      return false;
    }

    final bookingKey = '${userId}_${exhibitionId}_${visitDate.toIso8601String()}';
    if (_userBookings.contains(bookingKey)) {
      return false; // 已经预约
    }

    // 更新展览预约人数
    final index = _exhibitions.indexWhere((e) => e.id == exhibitionId);
    if (index != -1) {
      _exhibitions[index] = _exhibitions[index].copyWith(
        currentVisitors: _exhibitions[index].currentVisitors + 1,
      );
      _userBookings.add(bookingKey);
      return true;
    }
    
    return false;
  }

  /// 取消预约
  Future<bool> cancelBooking(String exhibitionId, String userId, DateTime visitDate) async {
    await Future.delayed(const Duration(milliseconds: 300));
    
    final bookingKey = '${userId}_${exhibitionId}_${visitDate.toIso8601String()}';
    if (!_userBookings.contains(bookingKey)) {
      return false; // 未预约
    }

    // 更新展览预约人数
    final index = _exhibitions.indexWhere((e) => e.id == exhibitionId);
    if (index != -1) {
      _exhibitions[index] = _exhibitions[index].copyWith(
        currentVisitors: _exhibitions[index].currentVisitors - 1,
      );
      _userBookings.remove(bookingKey);
      return true;
    }
    
    return false;
  }

  /// 检查用户是否已预约
  Future<bool> isUserBooked(String exhibitionId, String userId, DateTime visitDate) async {
    await Future.delayed(const Duration(milliseconds: 100));
    final bookingKey = '${userId}_${exhibitionId}_${visitDate.toIso8601String()}';
    return _userBookings.contains(bookingKey);
  }

  /// 收藏展览
  Future<bool> favoriteExhibition(String exhibitionId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 200));
    final favoriteKey = '${userId}_$exhibitionId';
    if (!_userFavorites.contains(favoriteKey)) {
      _userFavorites.add(favoriteKey);
      return true;
    }
    return false;
  }

  /// 取消收藏
  Future<bool> unfavoriteExhibition(String exhibitionId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 200));
    final favoriteKey = '${userId}_$exhibitionId';
    return _userFavorites.remove(favoriteKey);
  }

  /// 检查用户是否已收藏
  Future<bool> isExhibitionFavorited(String exhibitionId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 100));
    final favoriteKey = '${userId}_$exhibitionId';
    return _userFavorites.contains(favoriteKey);
  }

  /// 获取用户收藏的展览
  Future<List<Exhibition>> getUserFavoriteExhibitions(String userId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    final favoriteExhibitionIds = _userFavorites
        .where((key) => key.startsWith('${userId}_'))
        .map((key) => key.split('_')[1])
        .toList();
    
    return _exhibitions.where((e) => favoriteExhibitionIds.contains(e.id)).toList();
  }

  /// 获取用户预约的展览
  Future<List<Exhibition>> getUserBookedExhibitions(String userId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    final bookedExhibitionIds = _userBookings
        .where((key) => key.startsWith('${userId}_'))
        .map((key) => key.split('_')[1])
        .toSet() // 去重
        .toList();
    
    return _exhibitions.where((e) => bookedExhibitionIds.contains(e.id)).toList();
  }

  /// 获取展览统计信息
  Future<Map<String, int>> getExhibitionStats() async {
    await Future.delayed(const Duration(milliseconds: 200));
    return {
      'total': _exhibitions.length,
      'upcoming': _exhibitions.where((e) => e.status == ExhibitionStatus.upcoming).length,
      'ongoing': _exhibitions.where((e) => e.status == ExhibitionStatus.ongoing).length,
      'completed': _exhibitions.where((e) => e.status == ExhibitionStatus.completed).length,
      'featured': _exhibitions.where((e) => e.isFeatured).length,
    };
  }

  /// 获取展览类型统计
  Future<Map<String, int>> getTypeStats() async {
    await Future.delayed(const Duration(milliseconds: 200));
    final Map<String, int> stats = {};
    for (final exhibition in _exhibitions) {
      final typeText = exhibition.typeText;
      stats[typeText] = (stats[typeText] ?? 0) + 1;
    }
    return stats;
  }

  /// 获取虚拟展厅列表
  Future<List<Exhibition>> getVirtualTourExhibitions() async {
    await Future.delayed(const Duration(milliseconds: 300));
    return _exhibitions.where((e) => e.hasVirtualTour).toList();
  }

  /// 添加书签（收藏展览的别名方法）
  Future<bool> addBookmark(String exhibitionId, String userId) async {
    return await favoriteExhibition(exhibitionId, userId);
  }

  /// 移除书签（取消收藏展览的别名方法）
  Future<bool> removeBookmark(String exhibitionId, String userId) async {
    return await unfavoriteExhibition(exhibitionId, userId);
  }

  /// 获取用户参与情况
  Future<Map<String, dynamic>> getUserParticipation(String userId) async {
    await Future.delayed(const Duration(milliseconds: 200));
    
    final bookedExhibitions = await getUserBookedExhibitions(userId);
    final favoriteExhibitions = await getUserFavoriteExhibitions(userId);
    
    return {
      'booked_count': bookedExhibitions.length,
      'favorite_count': favoriteExhibitions.length,
      'booked_exhibitions': bookedExhibitions,
      'favorite_exhibitions': favoriteExhibitions,
    };
  }

  /// 清除所有数据（用于测试）
  void clearAllData() {
    _exhibitions.clear();
    _userBookings.clear();
    _userFavorites.clear();
  }
}